package cn.softgame.jserver.application;

import cn.softgame.jserver.application.connection.ConnectionFactory;
import cn.softgame.jserver.connector.data.ObjectType;
import cn.softgame.jserver.connector.data.QueueAddWorker;
import cn.softgame.jserver.connector.data.QueueTakeWorker;
import cn.softgame.jserver.connector.data.QueueWorker;
import cn.softgame.jserver.connector.data.StringType;
import cn.softgame.jserver.queue.MessageQueue;

/**
 * 连接接口，需要发送和接受数据时，使用本类。
 * 从ConnectionFactory获得本类实例
 * @author lenovo
 *
 */
public abstract class Connection {
	protected MessageQueue queue = null;
	protected int csType; // 连接类型，是客户端还是服务器端
	
	public void writeObject(Object obj) throws Exception{
		if(!isConnect()){
			throw new Exception("not connected");
		}
		try{
			QueueWorker worker = new QueueAddWorker(queue);
			ObjectType ot = new ObjectType(getWriteMsgType());
			ot.setContent(obj);
			ot.accept(worker);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public Object readObject() throws Exception{
		if(!isConnect()){
			throw new Exception("not connected");
		}
		try{
			QueueWorker worker = new QueueTakeWorker(queue);
			ObjectType ot = new ObjectType(getReadMsgType());
			ot.accept(worker);
			return ot.getContent();
		}catch(Exception e){
			e.printStackTrace();
			throw new Exception(e);
		}
	}
	
	public void writeString(String msg) throws Exception{
		if(!isConnect()){
			throw new Exception("not connected");
		}
		try{
			QueueWorker worker = new QueueAddWorker(queue);
			StringType st = new StringType(getWriteMsgType());
			st.setContent(msg);
			st.accept(worker);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public String readString() throws Exception{
		if(!isConnect()){
			throw new Exception("not connected");
		}
		try{
			QueueWorker worker = new QueueTakeWorker(queue);
			StringType st = new StringType(getReadMsgType());
			st.accept(worker);
			return st.getContent();
		}catch(Exception e){
			e.printStackTrace();
			throw new Exception(e);
		}
	}
	
	/**
	 * 根据是服务器应用还是客户端应用，设置写入Queue 中的信息类型
	 * 是request 还是response
	 * @return
	 */
	public int getWriteMsgType(){
		if(csType==ConnectionFactory.CLIENT){
			return QueueWorker.REQUEST;
		}else{
			return QueueWorker.RESPONSE;
		}
	}
	
	public int getReadMsgType(){
		if(csType==ConnectionFactory.CLIENT){
			return QueueWorker.RESPONSE;
		}else{
			return QueueWorker.REQUEST;
		}
	}
	
	public abstract void open(String url,int port) throws Exception;
	public abstract void close() throws Exception;
	public abstract boolean isConnect() throws Exception;
}
